<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
* TEXT class
*
* display all or random musings, quotes, paraphrases
*****/
class TEXT
{
// Constructor
	function TEXT($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/MISC.php");
		include_once("core/html/HTML.php");
		$this->html = new HTML();
		include_once("core/html/FORM.php");
		include_once("core/html/TABLE.php");
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/cite/CITE.php");
		$this->cite = new CITE($this->db, $this->vars);
		include_once("core/html/CLOSEPOPUP.php");
		$this->output = 'html';
	}
/**
* Display quotes and paraphrases for insertion into the SUWP
*
* @author Mark Grimshaw
*/
	function suwpMetadataDisplay($error = FALSE)
	{
		$this->template->setVar("heading", $this->messages->text("heading", "metadata"));
		$pString = $error ? $error : FALSE;
		$pString .= $this->displaySearchForm();
//		if($this->session->getVar("citeMeta_field"))
//			$pString .= $this->getMetadata();
//		$pString .= MISC::jsExternal('core/text/metadata.js');
		$this->template->setVar('body', $pString);
		new CLOSEPOPUP($this->template->process());
	}

/**
* Search/Select form for metadata
*
* @author Mark Grimshaw
*/
	function displaySearchForm()
	{
		include_once("core/list/SEARCHMETADATA.php");
		$searchMeta = new SEARCHMETADATA($this->db, $this->vars);
		include_once("core/list/SELECTMETADATA.php");
		$selectMeta = new SELECTMETADATA($this->db, $this->vars);
// Using user bibliography?
		$userBib = $this->session->getVar("mywikindx_bibliography_use");
		if($userBib)
		{
			$recordset = $this->db->select(array('WKX_user_bibliography'), array('title'), 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($userBib));
			$row = $this->db->fetchRow($recordset);
			$pString = MISC::p(MISC::span("(" . $this->messages->text("user", "bibliography") . ": " . 
				$row['title'] . ")", "hint"));
		}
		else if($this->session->getVar('setup_multiUser'))
			$pString = MISC::p(MISC::span("(" . $this->messages->text("user", "bibliography") . ": " . 
			$this->messages->text("user", "masterBib") . ")", "hint"));
		else
			$pString = '';
// Select form first
		$pString .= MISC::h($this->messages->text("heading", "searchMeta"), 3);
		$recordset = $this->db->select(array('WKX_database_summary'), array('totalResources'));
		if(!$this->db->fetchOne($recordset))
			return $this->messages->text('misc', 'noResources');
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
		$pString .= FORM::formHeaderName("suwpMetaProcess", "search");
		$this->radioButtons = FALSE;
// Types of metadata to search on
		$fields = array("quote"	=>	$this->messages->text("metadata", "quotes"),
				"quoteComment"	=>	$this->messages->text("metadata", "quoteComments"),
				"paraphrase"	=>	$this->messages->text("metadata", "paraphrases"),
				"paraphraseComment"	=>	$this->messages->text("metadata", "paraphraseComments"),
				"musing"	=>	$this->messages->text("metadata", "musings"),
			);
		$pString .= TABLE::td($this->makeFormMultiple("field", $fields, TRUE));
		$selectMeta->userBib = $userBib;
		$selectMeta->grabCreators();
		if($selectMeta->creator)
			$pString .= TABLE::td($this->makeFormMultiple("creator", $selectMeta->creator));
		else
			$pString .= TABLE::td("&nbsp;");
		$searchMeta->grabKeywords();
		if($searchMeta->keyword)
			$pString .= TABLE::td($this->makeFormMultiple("keyword", $searchMeta->keyword));
		else
			$pString .= TABLE::td("&nbsp;");
		$pString .= TABLE::trEnd();
		$pString .= TABLE::trStart();
		$pString .= $this->makeWordSearch();
		if(is_array($this->session->getArray("citeMeta")))
		{
			$this->session->clearArray("citeMeta");
			$reset = MISC::br() . MISC::br() . FORM::formHeader("suwpMetadataDisplay") . 
				FORM::formSubmit("Reset") . FORM::formEnd();
			$pString .= TABLE::td(FORM::formSubmit("Search") . FORM::formEnd() . $reset);
		}
		else
			$pString .= TABLE::td(FORM::formSubmit("Search") . MISC::br() . MISC::br() . 
			FORM::formReset() . FORM::formEnd());
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		return $pString;
	}
// make the word search fields
	function makeWordSearch()
	{
		$word = $this->session->issetVar("citeMeta_word") ? 
			$this->session->getVar("citeMeta_word") : FALSE;
		$checked = $this->session->issetVar("citeMeta_partial") ? 'CHECKED' : FALSE;
		$pString = TABLE::td(FORM::textInput($this->messages->text("search", "word"), "citeMeta_word", 
			$word, 40) . 
			MISC::p($this->messages->text("search", "partial") . ":&nbsp;&nbsp;" . 
			FORM::checkbox(FALSE, "citeMeta_partial", $checked)));
// array of search methods:
		$methods = array("OR"		=>	"OR",
				"AND"		=>	"AND",
				"exact"		=>	$this->messages->text("search", "exact"),
			);
		if($selected = $this->session->getVar("citeMeta_method"))
			$pString .= TABLE::td(FORM::selectedBoxValue(
			$this->messages->text("search", "search", " " . 
			$this->messages->text("search", "method")), "citeMeta_method", $methods, $selected, 3));
		else
			$pString .= TABLE::td(FORM::selectFBoxValue(
			$this->messages->text("search", "search", " " . 
			$this->messages->text("search", "method")), "citeMeta_method", $methods, 3));
		return $pString;
	}
// make a multiple select box
	function makeFormMultiple($type, $array, $noIgnore = FALSE)
	{
// add 0 => IGNORE to $array
		if(!$noIgnore)
		{
			$temp[0] = $this->messages->text("misc", "ignore");
			foreach($array as $key => $value)
				$temp[$key] = $value;
		}
		else
			$temp = $array;
		if($type == 'keyword')
			$label = 'member';
		else
			$label = 'search';
		if($selected = $this->session->getVar("citeMeta_" . $type))
		{
			$selectedArray = explode(",", $selected);
			$pString = FORM::selectedBoxValueMultiple(
				$this->messages->text("search", $label, " " . 
				$this->messages->text("search", $type)), 
				"citeMeta_" . $type, $temp, $selectedArray, 5);
		}
		else
		{
// If $type == 'field', select all fields as default
			if($type == 'field')
			{
				$pString = FORM::selectedBoxValueMultiple(
					$this->messages->text("search", $label, " " . 
					$this->messages->text("search", $type)), 
					"citeMeta_" . 'field', $temp, array_keys($array), 5);
			}
			else
				$pString = FORM::selectFBoxValueMultiple(
					$this->messages->text("search", $label, " " . 
					$this->messages->text("search", $type)), 
					"citeMeta_" . $type, $temp, 5);
		}
		$pString .= MISC::br() . $this->messages->text("hint", "multiples") . MISC::br();
		$pString .= $this->radioButtons . MISC::br();
		return $pString;
	}
/**
* Process SUWP metadata search form
*
* @author Mark Grimshaw
*/
	function suwpMetaProcess()
	{
		include_once("core/list/SEARCHMETADATA.php");
		$searchMeta = new SEARCHMETADATA($this->db, $this->vars);
		include_once("core/list/LISTCOMMON.php");
		$common = new LISTCOMMON($this->db, $this->vars);
		$input = $this->suwpCheckInput();
		include_once("core/list/LISTMETADATACOMMON.php");
		$this->metadataCommon = new LISTMETADATACOMMON($this->db, $this->vars, 'html');
		$this->metadataCommon->suwpCite = TRUE;
		$words = array();
		$conditionArray = $this->conditionQ = $this->conditionQC = $this->conditionP = $this->conditionPC = 
			$this->conditionM = $this->patterns = array();
		$this->condition = FALSE;
		if(array_key_exists("citeMeta_word", $this->vars) && trim($this->vars["citeMeta_word"]))
		{
			$searchMeta->parseWord($input);
			$words = $searchMeta->words;
			$searchTerms = explode(",", $this->session->getVar('searchMeta_highlight'));
			foreach($searchTerms as $term)
				$this->patterns[] = "/($term)/i";
		}
		$this->suwpFieldSql($input, $words);
		if(array_key_exists('creator', $input))
		{
			include_once("core/creator/CREATOR.php");
			$creator = new CREATOR($this->db);
			$conditionArray[] = $creator->selectCondition($input);
		}
		$this->kwq = $this->kwp = $this->kwm = FALSE;
		if(array_key_exists('keyword', $input))
		{
			include_once("core/keyword/KEYWORD.php");
			$kw = new KEYWORD($this->db);
			if($c = $kw->selectConditionMetadata($input, 'quote'))
			{
				$this->conditionQ[] = "($c)";
				$this->conditionQC[] = "($c)";
			}
			if($c = $kw->selectConditionMetadata($input, 'paraphrase'))
			{
				$this->conditionP[] = "($c)";
				$this->conditionPC[] = "($c)";
			}
			if($c = $kw->selectConditionMetadata($input, 'musing'))
				$this->conditionM[] = "($c)";
		}
		if($bibCondition = $common->userBibCondition())
			$conditionArray[] = " (" . $bibCondition . ")";
		if(!empty($conditionArray))
			$this->condition = " WHERE " . implode(" AND ", $conditionArray);
		$results = $this->suwpExecuteStmts();
		$this->template->setVar("heading", $this->messages->text("heading", "metadata"));
		$pString = $this->displaySearchForm() . $results;
		$this->template->setVar('body', $pString);
		include_once("core/html/CLOSEPOPUP.php");
		new CLOSEPOPUP($this->template->process());
	}
// Execute each statement and concatenate into string
	function suwpExecuteStmts()
	{
		include_once("core/user/USER.php");
		$this->user = new USER($this->db);
		include_once("core/cite/CITE.php");
		$cite = new CITE($this->db, $this->vars);
		$pString = FALSE;
		$this->metadataCommon->citeIndex = 1;
		$this->metadataCommon->radioButtonFirst = TRUE;
		$this->userId = $this->session->getVar('setup_userId');
		$condition = FALSE;
		$this->resourceTitles = array();
		if(!$this->condition)
		{
			$basicCondition = " WHERE ";
			$join = FALSE;
		}
		else
		{
			$basicCondition = $this->condition;
			$join = "AND";
		}
		$order = " ORDER BY " . 
			$this->db->tidyInputClause('surname') . "," . 
			$this->db->tidyInputClause('year1') . "," . 
			$this->db->tidyInputClause('title') . "," . 
			$this->db->tidyInputClause('page_start') . '+ 0'; // read varchar as integer
		if($this->stmtQuote)
		{
			$condition = $basicCondition;
			if(!empty($this->conditionQ))
				 $condition .= " $join (" . implode(" AND ", $this->conditionQ) . ")";
			if($condition == " WHERE ")
				$condition = FALSE;
			$stmt = $this->stmtQuote . $condition . $order;
//			$pString .= $this->suwpExecuteThisStmt($stmt, "text", "quotes");
			$this->metadataCommon->executeThisStmt($stmt, "text", "quotes", 
				$this->allIds, $this->userId, $this->patterns);
		}
		if($this->stmtQuoteComment)
		{
			$condition = $basicCondition;
			if(!empty($this->conditionQC))
				$condition .= " $join (" . implode(" AND ", $this->conditionQC) . ")";
			if($condition == " WHERE ")
				$condition = FALSE;
			$stmt = $this->stmtQuoteComment . $condition . $order;
//			$pString .= $this->suwpExecuteThisStmt($stmt, "comment", "quoteComments");
			$this->metadataCommon->executeThisStmt($stmt, "comment", 
				"quoteComments", $this->allIds, $this->userId, $this->patterns);
		}
		$pString = $this->metadataCommon->format('quotes');
		$pString .= $this->metadataCommon->format('quoteComments');
		if($this->stmtParaphrase)
		{
			$condition = $basicCondition;
			if(!empty($this->conditionP))
				$condition .= " $join (" . implode(" AND ", $this->conditionP) . ")";
			if($condition == " WHERE ")
				$condition = FALSE;
			$stmt = $this->stmtParaphrase . $condition . $order;
			$this->metadataCommon->executeThisStmt($stmt, "text", 
				"paraphrases", $this->allIds, $this->userId, $this->patterns);
//			$pString .= $this->suwpExecuteThisStmt($stmt, "text", "paraphrases");
		}
		if($this->stmtParaphraseComment)
		{
			$condition = $basicCondition;
			if(!empty($this->conditionPC))
				$condition .= " $join (" . implode(" AND ", $this->conditionPC) . ")";
			if($condition == " WHERE ")
				$condition = FALSE;
			$stmt = $this->stmtParaphraseComment . $condition . $order;
			$this->metadataCommon->executeThisStmt($stmt, "comment", 
				"paraphraseComments", $this->allIds, $this->userId, $this->patterns);
//			$pString .= $this->suwpExecuteThisStmt($stmt, "comment", "paraphraseComments");
		}
		$pString .= $this->metadataCommon->format('paraphrases');
		$pString .= $this->metadataCommon->format('paraphraseComments');
		if($this->stmtMusing)
		{
			$condition = $basicCondition;
			if(!empty($this->conditionM))
				$condition .= " $join (" . implode(" AND ", $this->conditionM) . ")";
			if($condition == " WHERE ")
				$condition = FALSE;
			$stmt = $this->stmtMusing . $condition . $order;
			$this->metadataCommon->executeThisStmt($stmt, "text", "musings", 
				$this->allIds, $this->userId, $this->patterns);
//			$pString .= $this->suwpExecuteThisStmt($stmt, "text", "musings");
		}
		$pString .= $this->metadataCommon->format('musings');
		if(!$pString)
			return MISC::br() . MISC::hr() . MISC::br() . $this->messages->text("resources", "noMetadata");
		$pString = MISC::br() . MISC::hr() . 
			FORM::formHeaderName("", "js", "onsubmit=\"submitForm();\"") . $pString;
		$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
//		$pString .= MISC::br() . "&nbsp;" . MISC::br();
		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$pString .= TABLE::trStart();
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
// Include JavaScript file
		$execute = "function submitForm() {\n  var metadataForm = document.getElementsByTagName('form').item('js');\n  var metadataString = handleMetadataFormRte(metadataForm);\n  window.opener.insertMetadataRte(metadataString);\n  window.close();\n}";
		$pString .= MISC::jsExternal('core/wp/JsFormatBar/JavaScript/JavaScript.js', $execute);
		$citeTagOnly = $this->messages->text('wp', 'citeTagOnly') . ':&nbsp;&nbsp;' . 
			FORM::checkbox(FALSE, 'citeTagOnly');
		$pString .= MISC::p(FORM::formSubmit("Cite") . '&nbsp;&nbsp;' . $citeTagOnly . FORM::formEnd());
		return $pString;
	}
// Grab resource from database
	function grabResource($id)
	{
		include_once("core/sql/STATEMENTS.php");
		$stmt = new STATEMENTS($this->db);
		$sql = $this->db->selectNoExecute(array("WKX_resource"), $stmt->listFields(),
			$stmt->selectJoin());
		$sql .= " WHERE WKX_resource.id=" . $this->db->tidyInput($id);
		$recordset = $this->db->query($sql);
		if(!$this->db->numRows($recordset))
			$this->badInput($this->messages->text("resources", "noResult"));
		include_once("core/styles/BIBSTYLE.php");
		$bibStyle = new BIBSTYLE($this->db, "html");
		return $bibStyle->process($this->db->fetchRow($recordset));
	}
// Execute a SQL statement for a particule metadata field
	function suwpExecuteThisStmt($stmt, $textField, $field)
	{
		$recordSet = $this->db->query($stmt);
		$index = 0;
		$pString = $string = FALSE;
		$first = TRUE;
		$titlePrinted = array();
		if($this->db->numRows($recordSet))
		{
			while($row = $this->db->loopRecordSet($recordSet))
			{
				if((($field == 'quoteComments') && ($row['quotePrivate'] == 'Y') && 
					($this->userId != $row['addUserIdQuote']))
					||
					(($field == 'paraphraseComments') && ($row['paraphrasePrivate'] == 'Y') && 
					($this->userId != $row['addUserIdParaphrase']))
					||
					(($field == 'musings') && ($row['musingPrivate'] == 'Y') && 
					($this->userId != $row['addUserIdMusing']))
					)
					continue;
				if($first)
				{
					$string = TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart() . 
						"&nbsp;" . MISC::p(MISC::h($this->messages->text("metadata", $field, 3)));
					$string .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
					if($this->radioButtonFirst)
						$radio = FORM::radioButton(FALSE, 'cite', $this->citeIndex, TRUE);
					else
						$radio = FORM::radioButton(FALSE, 'cite', $this->citeIndex);
					$first = FALSE;
					$this->radioButtonFirst = FALSE;
				}
				else
					$radio = FORM::radioButton(FALSE, 'cite', $this->citeIndex);
				$pages = FALSE;
				$text = $this->convertBBCode(utf8_decode(stripslashes($row[$textField])));
				if(($field == 'quotes') || ($field == 'paraphrases'))
				{
					if($row['page_start'])
						$pages = ":" . stripslashes($row['page_start']);
					if($row['page_end'])
						$pages .= "-" . stripslashes($row['page_end']);
					$citeTag = rawurlencode(' [cite]' . $row['resourceId'] . $pages . '[/cite]');
					$string .= FORM::hidden("hidden_" . $this->citeIndex, $text . $citeTag);
				}
				else
					$string .= FORM::hidden("hidden_" . $this->citeIndex, rawurlencode($text));
				$string .= TABLE::trStart();
				if(!array_key_exists($row['resourceId'], $this->resourceTitles))
					$this->resourceTitles[$row['resourceId']] = $this->grabResource($row['resourceId']);
				if(!array_key_exists($row['resourceId'], $titlePrinted))
				{
					$titlePrinted[$row['resourceId']] = TRUE;
					$string .= TABLE::td($this->resourceTitles[$row['resourceId']], 'metaResourceDetails', 
						FALSE, 'top');
					$string .= TABLE::td("&nbsp;", 'metaResourceDetails');
					$index = 0;
					$string .= TABLE::trEnd() . TABLE::trStart();
				}
				$class = $index % 2 ? 'alternate2' : 'alternate1';
				if(!empty($this->patterns))
					$text = preg_replace($this->patterns, MISC::span("$1", "highlight"), $row[$textField]);
				$string .= TABLE::td($this->html->codeToHtml($this->cite->parseCitations
					(stripslashes($text), 'html')), $class);
				$string .= TABLE::td($radio, $class, "right");
				$string .= TABLE::trEnd();
				++$index;
				++$this->citeIndex;
			}
			if($string)
				$pString .= $string . TABLE::tableEnd();
		}
		return $pString;
	}
/**
* Devise form for quotes and paraphrases for insertion into the SUWP.  Not used anymore?
*
* @author Mark Grimshaw
*/
	function getMetadata($metaSql)
	{
		$metaSql = stripSlashes(base64_decode($metaSql));
		$recordsetQ = $this->db->select(array('WKX_resource_quote'), 
			array('resourceId', 'text', 'page_start', 'page_end'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_quote_text') . " ON " . 
			$this->db->formatfield("WKX_resource_quote_text.id") . "=" . 
			$this->db->formatfield("WKX_resource_quote.id") . 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_timestamp') . " ON " . 
			$this->db->formatfield("WKX_resource_quote.resourceId") . "=" . 
			$this->db->formatfield("WKX_resource_timestamp.id") .  
			" ORDER BY " . $this->db->tidyInputClause("timestamp") . " DESC");
		$recordsetP = $this->db->select(array('WKX_resource_paraphrase'), 
			array('resourceId', 'text', 'page_start', 'page_end'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_paraphrase_text') . " ON " . 
			$this->db->formatfield("WKX_resource_paraphrase_text.id") . "=" . 
			$this->db->formatfield("WKX_resource_paraphrase.id") . 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_timestamp') . " ON " . 
			$this->db->formatfield("WKX_resource_paraphrase.resourceId") . "=" . 
			$this->db->formatfield("WKX_resource_timestamp.id") .  
			" ORDER BY " . $this->db->tidyInputClause("timestamp") . " DESC");
		if(!$this->db->numRows($recordsetQ) && !$this->db->numRows($recordsetP))
			$this->badInputPopUp($this->messages->text("resources", "noMetadata"));
		$index = 0;
		$citeIndex = 1;
		$this->template->setVar('formStart', FORM::formHeader("", "onsubmit=\"submitForm();\""));
		$pString = MISC::p(MISC::h($this->messages->text('viewResource', 'quotes')));
		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$first = TRUE;
		while($row = $this->db->loopRecordSet($recordsetQ)) // quotes
		{
			if($first)
			{
				$radio = FORM::radioButton(FALSE, 'cite', $citeIndex, TRUE);
				$first = FALSE;
			}
			else
				$radio = FORM::radioButton(FALSE, 'cite', $citeIndex);
			$pages = FALSE;
			$text = $this->convertBBCode(utf8_decode(stripslashes($row['text'])));
			if($row['page_start'])
				$pages = ":" . stripslashes($row['page_start']);
			if($row['page_end'])
				$pages .= "-" . stripslashes($row['page_end']);
			$citeTag = rawurlencode(' [cite]' . $row['resourceId'] . $pages . '[/cite]');
			$pString .= FORM::hidden("hidden_$citeIndex", rawurlencode($text) . $citeTag);
			$pString .= FORM::hidden("hiddenCiteTag_citeIndex", $citeTag);
			$class = $index % 2 ? 'alternate2' : 'alternate1';
			$pString .= TABLE::trStart();
			$pString .= TABLE::td($this->html->codeToHtml($this->cite->parseCitations
				(stripslashes($row['text']), 'html')), $class);
			$pString .= TABLE::td($radio, $class, "right");
			$pString .= TABLE::trEnd();
			++$index;
			++$citeIndex;
		}
		$pString .= TABLE::tableEnd();
		$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
		$pString .= MISC::p(MISC::br() . "&nbsp;" . MISC::br() . 
			MISC::h($this->messages->text('viewResource', 'paraphrases')));
		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		while($row = $this->db->loopRecordSet($recordsetP)) // paraphrases
		{
			if($first)
			{
				$radio = FORM::radioButton(FALSE, 'cite', $citeIndex, TRUE);
				$first = FALSE;
			}
			else
				$radio = FORM::radioButton(FALSE, 'cite', $citeIndex);
			$pages = FALSE;
			$text = $this->convertBBCode(utf8_decode(stripslashes($row['text'])));
			if($row['page_start'])
				$pages = ":" . stripslashes($row['page_start']);
			if($row['page_end'])
				$pages .= "-" . stripslashes($row['page_end']);
			$citeTag = rawurlencode(' [cite]' . $row['resourceId'] . $pages . '[/cite]');
			$pString .= FORM::hidden("hidden_$citeIndex", rawurlencode($text) . $citeTag);
			$pString .= FORM::hidden("hiddenCiteTag_$citeIndex", $citeTag);
			$class = $index % 2 ? 'alternate2' : 'alternate1';
			$pString .= TABLE::trStart();
			$pString .= TABLE::td($this->html->codeToHtml($this->cite->parseCitations
				(stripslashes($row['text']), 'html')), $class);
			$pString .= TABLE::td($radio, $class, "right");
			$pString .= TABLE::trEnd();
			++$index;
			++$citeIndex;
		}
		$pString .= TABLE::tableEnd();
		$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
		$pString .= MISC::br() . "&nbsp;" . MISC::br();
		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$pString .= TABLE::trStart();
		$pString .= TABLE::td(FORM::formSubmit("Cite"));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$pString .= $this->template->setVar('formEnd', FORM::formEnd());
// Include JavaScript file
		$execute = "function submitForm() {\n  var metadataForm = document.getElementsByTagName('form').item(0);\n  var metadataString = handleMetadataFormRte(metadataForm);\n  window.opener.insertMetadataRte(metadataString);\n  window.close();\n}";
		$pString .= MISC::jsExternal('core/wp/JsFormatBar/JavaScript/JavaScript.js', $execute);
		return $pString;
	}
/**
* Convert BBCode to design mode HTML for quotes and paraphrases for insertion into the SUWP.
* Some simplification occurs
*
* @author Mark Grimshaw
*/
	function convertBBCode($text)
	{
		$pattern = array(
							"/\[b\](.*?)\[\/b\]/si",
							"/\[u\](.*?)\[\/u\]/si",
							"/\[i\](.*?)\[\/i\]/si",
							"/\[sup\](.*?)\[\/sup\]/si",
							"/\[sub\](.*?)\[\/sub\]/si",
							"/\[size=(.*?)\](.*?)\[\/size\]/is",
							"/\[color=(.*?)\](.*?)\[\/color\]/is",
							"/(?<!\http:\/\/)(www\.)(\S+)/i", // watch out for 'www' in image/url tags!
							"/\[url\](.*?)\[\/url\]/is",
							"/\[url=(.*?)\](.*?)\[\/url\]/is",
							"/\[email\](.*?)\[\/email\]/is",
							"/(ftp\.)(\S+)/i",
							"/\[img\](.*?)\[\/img\]/is",
							"/\[list\](.*?)\[\/list\]/is",
							"/\[list.*?\](.*?)\[\/list\]/is",
							"/\[\*\]/is",
//							"/\[.*?\]|\[\/.*?\]/si",
						);
		$change = array(
							"<span style=\"font-weight: bold;\">$1</span>",
							"<span style=\"text-decoration: underline;\">$1</span>",
							"<span style=\"font-style: italic;\">$1</span>",
							"<sup>$1</sup>",
							"<sub>$1</sub>",
							"$2",
							"$2",
							"<a href=\"http://\\1\\2\">\\1\\2</a>",
							"<a href=\"$1\">$1</a>",
							"<a href=\"$1\">$2</a>",
							"<a href=\"mailto:$1\">$1</a>",
							"\\1\\2",
							"<img src=\"$1\" border=\"0\" />",
							"<ul>$1</ul>",
							"<ol>$1</ol>",
							"<li>",
//							"",
						);
		return preg_replace($pattern, $change, $text);
	}
// If $noMenu, display Text submenu links
	function display($noMenu = FALSE)
	{
		$this->template->setVar('heading', $this->messages->text("heading", "text"));
		if($noMenu)
		{
			include_once("core/html/MENU.php");
			$menu = new MENU();
			$pString = $menu->noMenu('metadata');
			$this->template->setVar('noMenu', $pString);
			return $this->template->process();
		}
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// show all Musings -- no longer in use
	function allMusings()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "text"));
		$recordset = $this->db->select(array('WKX_resource_musing'), 
			array('resourceId', 'text', 'musingPrivate', 'addUserIdMusing'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_musing_text') . " ON " . 
			$this->db->formatfield("WKX_resource_musing_text.id") . "=" . 
			$this->db->formatfield("WKX_resource_musing.id") . 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_timestamp') . " ON " . 
			$this->db->formatfield("WKX_resource_musing.resourceId") . "=" . 
			$this->db->formatfield("WKX_resource_timestamp.id") .  
			" ORDER BY " . $this->db->tidyInputClause("WKX_resource_timestamp.timestamp") . " DESC");
		if(!$this->db->numRows($recordset))
			$this->badInput($this->messages->text("resources", "noMusing"));
		$index = 0;
		$pString = TABLE::tableStart(FALSE, 0, 0, 0, "left");
		while($row = $this->db->loopRecordSet($recordset))
		{
			if(($row['musingPrivate'] == 'Y') && 
			($this->session->getVar('setup_userId') != $row['addUserIdMusing']))
				continue;
			$class = $index % 2 ? 'alternate2' : 'alternate1';
			$pString .= $this->dataRow($row['text'], $row['resourceId'], $class);
			$index++;
		}
		if(!$index)
			$this->badInput($this->messages->text("resources", "noMusing"));
		$pString .= TABLE::tableEnd();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// show random Musing
	function randomMusing()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "text"));
		$sql = $this->db->selectNoExecute(array('WKX_resource_musing'), 
			array('resourceId', 'text', 'musingPrivate', 'addUserIdMusing'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_musing_text') . " ON " . 
			$this->db->formatfield("WKX_resource_musing_text.id") . "=" . 
			$this->db->formatfield("WKX_resource_musing.id") . 
			" WHERE " . 
			$this->db->formatfield("addUserIdMusing") . "=" . 
			$this->db->tidyInput($this->session->getVar('setup_userId')) . 
			" OR " . 
			$this->db->formatfield("musingPrivate") . "=" . 
			$this->db->tidyInput('N') . 
			" ORDER BY RAND()");
		$recordset = $this->db->limit($sql, 1, 0);
		if(!$this->db->numRows($recordset))
			$this->badInput($this->messages->text("resources", "noMusing"));
		$row = $this->db->fetchRow($recordset);
		$pString = TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$pString .= $this->nextRandomLink("randomMusing");
		$pString .= $this->dataRow($row['text'], $row['resourceId'], 'alternate1');
		$pString .= TABLE::tableEnd();
		$this->template->setVar('body', $pString);
		$this->session->delVar("list_allIds");
		return $this->template->process();
	}
// show all Paraphrases -- no longer in use
	function allParaphrases()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "text"));
		$recordset = $this->db->select(array('WKX_resource_paraphrase'), 
			array('resourceId', 'text'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_paraphrase_text') . " ON " . 
			$this->db->formatfield("WKX_resource_paraphrase_text.id") . "=" . 
			$this->db->formatfield("WKX_resource_paraphrase.id") . 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_timestamp') . " ON " . 
			$this->db->formatfield("WKX_resource_paraphrase.resourceId") . "=" . 
			$this->db->formatfield("WKX_resource_timestamp.id") .  
			" ORDER BY " . $this->db->tidyInputClause("timestamp") . " DESC");
		if(!$this->db->numRows($recordset))
			$this->badInput($this->messages->text("resources", "noParaphrase"));
		$index = 0;
		$pString = TABLE::tableStart(FALSE, 0, 0, 0, "left");
		while($row = $this->db->loopRecordSet($recordset))
		{
			$class = $index % 2 ? 'alternate2' : 'alternate1';
			$pString .= $this->dataRow($row['text'], $row['resourceId'], $class);
			$index++;
		}
		$pString .= TABLE::tableEnd();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// show random Paraphrase
	function randomParaphrase()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "text"));
		$sql = $this->db->selectNoExecute(array('WKX_resource_paraphrase'), 
			array('resourceId', 'text'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_paraphrase_text') . " ON " . 
			$this->db->formatfield("WKX_resource_paraphrase_text.id") . "=" . 
			$this->db->formatfield("WKX_resource_paraphrase.id") . " ORDER BY RAND()");
		$recordset = $this->db->limit($sql, 1, 0);
		if(!$this->db->numRows($recordset))
			$this->badInput($this->messages->text("resources", "noParaphrase"));
		$row = $this->db->fetchRow($recordset);
		$pString = TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$pString .= $this->nextRandomLink("randomParaphrase");
		$pString .= $this->dataRow($row['text'], $row['resourceId'], 'alternate1');
		$pString .= TABLE::tableEnd();
		$this->template->setVar('body', $pString);
		$this->session->delVar("list_allIds");
		return $this->template->process();
	}
// show all Quotes -- no longer in use
	function allQuotes()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "text"));
		$recordset = $this->db->select(array('WKX_resource_quote'), 
			array('resourceId', 'text'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_quote_text') . " ON " . 
			$this->db->formatfield("WKX_resource_quote_text.id") . "=" . 
			$this->db->formatfield("WKX_resource_quote.id") . 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_timestamp') . " ON " . 
			$this->db->formatfield("WKX_resource_quote.resourceId") . "=" . 
			$this->db->formatfield("WKX_resource_timestamp.id") .  
			" ORDER BY " . $this->db->tidyInputClause("timestamp") . " DESC");
		if(!$this->db->numRows($recordset))
			$this->badInput($this->messages->text("resources", "noQuote"));
		$index = 0;
		$pString = TABLE::tableStart(FALSE, 0, 0, 0, "left");
		while($row = $this->db->loopRecordSet($recordset))
		{
			$class = $index % 2 ? 'alternate2' : 'alternate1';
			$pString .= $this->dataRow($row['text'], $row['resourceId'], $class);
			$index++;
		}
		$pString .= TABLE::tableEnd();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// show random Quote
	function randomQuote()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "text"));
		$sql = $this->db->selectNoExecute(array('WKX_resource_quote'), 
			array('resourceId', 'text'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_quote_text') . " ON " . 
			$this->db->formatfield("WKX_resource_quote_text.id") . "=" . 
			$this->db->formatfield("WKX_resource_quote.id") . " ORDER BY RAND()");
		$recordset = $this->db->limit($sql, 1, 0);
		if(!$this->db->numRows($recordset))
			$this->badInput($this->messages->text("resources", "noQuote"));
		$row = $this->db->fetchRow($recordset);
		$pString = TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$pString .= $this->nextRandomLink("randomQuote");
		$pString .= $this->dataRow($row['text'], $row['resourceId'], 'alternate1');
		$pString .= TABLE::tableEnd();
		$this->template->setVar('body', $pString);
		$this->session->delVar("list_allIds");
		return $this->template->process();
	}
// Show randmon metadata hyperlink
	function nextRandomLink($action)
	{
// type of CSS class required.
		include_once("core/icons/LOADICONS.php");
		$icons = new LOADICONS();
		$icons->getIconInfo("next");
		$nextClass = $icons->nextExists ? "imgLink" : "link";
		$td = MISC::a($nextClass, $icons->next, "index.php?action=$action");
		return TABLE::trStart() . TABLE::td($td, FALSE, "center") . TABLE::trEnd();
	}
// display a table row of data
	function dataRow($text, $id, $class, $patterns = FALSE, $icons = TRUE)
	{
// Load icons
		if($icons)
		{
			include_once("core/icons/LOADICONS.php");
			$icons = new LOADICONS();
			$icons->getIconInfo("view");
			$viewEditLink = $icons->viewExists ? "imgLink" : "link";
			$view = MISC::a("$viewEditLink", "&nbsp;" . $icons->view . "&nbsp;", 
				"index.php?action=resourceView" . htmlentities("&id=" . $id . "&access=1"));
		}
		else
			$view = "&nbsp;";
		$pString = TABLE::trStart();
		$td = $this->cite->parseCitations($this->html->dbToHtmlTidy($text), $this->output);
		if(!empty($patterns))
			$td = preg_replace($patterns, MISC::span("$1", "highlight"), $td);
		$pString .= TABLE::td($td, $class);
		$pString .= TABLE::td($view, $class, "right");
		$pString .= TABLE::trEnd();
		return $pString;
	}
// create SQL for SUWP
	function suwpFieldSql($input, $words)
	{
		if(!array_key_exists('field', $input))
			return;
		$this->stmtQuote = $this->stmtQuoteComment = $this->stmtParaphrase = $this->stmtParaphraseComment = 
			$this->stmtMusing = FALSE;
		$mainJoin = " LEFT JOIN " . $this->db->formatTable('WKX_resource') . 
					" ON " . $this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_creator') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_creator') . " ON " . 
					$this->db->formatfield("WKX_resource_creator.creator1") . "=" . 
					$this->db->formatfield("WKX_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_year') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_year.id");
		$fields = explode(",", $input['field']);
		foreach($fields as $field)
		{
			$conditionArray = array();
			if($field == 'quote')
			{
				if(!empty($words))
				{
					foreach($words as $word)
						$conditionArray[] = $this->db->formatfield("text") . $word;
					$this->conditionQ[] = "(" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				}
				$this->stmtQuote = $this->db->selectNoExecute(array('WKX_resource_quote'), 
					array(array("WKX_resource_quote.id" => 'quoteId'), 
						'resourceId', 'text', 'page_start', 'page_end'), 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote_text") .  
						" ON " . $this->db->formatfield("WKX_resource_quote.id") . "=" . 
						$this->db->formatfield("WKX_resource_quote_text.id") . 
					$mainJoin);
			}
			else if($field == 'quoteComment')
			{
				if(!empty($words))
				{
					foreach($words as $word)
						$conditionArray[] = $this->db->formatfield("comment") . $word;
					$this->conditionQC[] = "(" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				}
				$this->stmtQuoteComment = $this->db->selectNoExecute(array('WKX_resource_quote_comment'), 
					array(array("WKX_resource_quote_comment.id" => 'commentId'), 'resourceId', 
						'comment', 'quoteId', 'page_start', 'page_end', 
						'quotePrivate', 'WKX_resource_quote_comment.addUserIdQuote'), 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote") .  
						" ON " . $this->db->formatfield("WKX_resource_quote.id") . "=" . 
						$this->db->formatfield("WKX_resource_quote_comment.quoteId") . 
					$mainJoin);
			}
			else if($field == 'paraphrase')
			{
				if(!empty($words))
				{
					foreach($words as $word)
						$conditionArray[] = $this->db->formatfield("text") . $word;
					$this->conditionP[] = "(" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				}
				$this->stmtParaphrase = $this->db->selectNoExecute(array('WKX_resource_paraphrase'), 
					array(array("WKX_resource_paraphrase.id" => 'paraphraseId'), 
						'resourceId', 'text', 'page_start', 'page_end'), 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase_text") .  
						" ON " . $this->db->formatfield("WKX_resource_paraphrase.id") . "=" . 
						$this->db->formatfield("WKX_resource_paraphrase_text.id") . 
					$mainJoin);
			}
			else if($field == 'paraphraseComment')
			{
				if(!empty($words))
				{
					foreach($words as $word)
						$conditionArray[] = $this->db->formatfield("comment") . $word;
					$this->conditionPC[] = "(" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				}
				$this->stmtParaphraseComment = 
					$this->db->selectNoExecute(array('WKX_resource_paraphrase_comment'), 
					array(array("WKX_resource_paraphrase_comment.id" => 'commentId'), 
						'paraphraseId', 'resourceId', 'comment', 'paraphrasePrivate', 
						'WKX_resource_paraphrase_comment.addUserIdParaphrase', 'page_start', 'page_end'), 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase") .  
						" ON " . $this->db->formatfield("WKX_resource_paraphrase.id") . "=" . 
						$this->db->formatfield("WKX_resource_paraphrase_comment.paraphraseId") . 
					$mainJoin);
			}
			else if($field == 'musing')
			{
				if(!empty($words))
				{
					foreach($words as $word)
						$conditionArray[] = $this->db->formatfield("text") . $word;
					$this->conditionM[] = "(" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				}
				$this->stmtMusing = $this->db->selectNoExecute(array('WKX_resource_musing'), 
					array(array("WKX_resource_musing_text.id" => 'commentId'), 
						'resourceId', 'text', 'musingPrivate', 'addUserIdMusing', 'page_start', 'page_end'), 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_musing_text") .  
						" ON " . $this->db->formatfield("WKX_resource_musing.id") . "=" . 
						$this->db->formatfield("WKX_resource_musing_text.id") . 
					$mainJoin);
			}
		}
	}
// write SUWP search input to session
	function writeSession()
	{
// First, write all input with 'search_' prefix to session
		foreach($this->vars as $key => $value)
		{
			if(preg_match("/^citeMeta_/", $key))
			{
// Is this a multiple select box input?  If so, multiple choices are written to session as 
// comma-delimited string (no spaces).
// Don't write any FALSE or '0' values.
				if(is_array($value))
				{
					if(!$value[0] || ($value[0] == $this->messages->text("misc", "ignore")))
						unset($value[0]);
					if(empty($value))
					{
						$this->session->delVar($key);
						continue;
					}
					$value = implode(",", $value);
				}
				if(!trim($value))
					continue;
				$temp[$key] = trim($value);
			}
		}
// remove search_partial and search_word if not checked or empty
		if(isset($temp))
		{
			if(!array_key_exists('citeMeta_partial', $temp))
				$this->session->delVar('citeMeta_partial');
			if(!array_key_exists('citeMeta_word', $temp))
				$this->session->delVar('citeMeta_word');
			if(isset($temp))
				$this->session->writeArray($temp);
		}
	}
// validate user input for SUWP metadata insert
	function suwpCheckInput()
	{
		$this->writeSession();
/*		if(array_key_exists("citeMeta_method", $this->vars) && $this->vars["citeMeta_method"])
			$type = $this->vars["citeMeta_method"];
		else if($this->session->issetVar('citeMeta_method'))
			$type = $this->session->getVar("citeMeta_method");
		else
			$this->badInput($this->errors->text("inputError", "missing"));
*/		if(array_key_exists("citeMeta_field", $this->vars) && $this->vars["citeMeta_field"])
			$null = $this->vars["citeMeta_field"];
		else if($this->session->issetVar('citeMeta_field'))
			$null = $this->session->getVar("citeMeta_field");
		else
			$this->badInputPopUp($this->errors->text("inputError", "missing"));
//		if((array_key_exists("searchMeta_word", $this->vars) && !trim($this->vars["searchMeta_word"])) 
//		|| !$this->session->getVar("searchMeta_word"))
//			$this->badInput($this->errors->text("inputError", "missing"));
		return $this->session->getArray("citeMeta");
	}
// Error handling
	function badInput($error)
	{
		include_once("core/html/CLOSE.php");
		$this->template->setVar('body', $error);
		new CLOSE($this->db, $this->template->process());
	}
// Error handling for pop-up window
	function badInputPopUp($error)
	{
		$this->suwpMetadataDisplay($error);
//		include_once("core/html/CLOSEPOPUP.php");
//		$this->template->setVar('body', $error);
//		new CLOSEPOPUP($this->db, $this->template->process());
	}
}
?>
